<template>
	<view class="order" style="padding-top:60rpx;">
        <step :active="1"></step>
		<view class="address-container">
			<view class="addressPush-list">
				<view class="li">
					<view class="h3">收货人:</view>
					<view class="div">
						<input type="text" v-model="formData.name" value="" placeholder="请准确填写收货人" />
					</view>	
				</view>
				<view class="li">
					<view class="h3">手机号码:</view>
					<view class="div">
						<input type="text" maxlength="11" v-model="formData.mobile" value="" placeholder="请准确填写手机号码" />
					</view>	
				</view>
				<view class="li">
					<view class="h3">配送区域:</view>
					<view class="address-input div" @tap="openPicker">
                        <input type="text"  name="area" :value="formData.area" disabled placeholder="请选择所在地区"></input>
					</view>
				</view>
				<view class="li">
					<view class="h3">详细地址:</view>
					<view class="div">
						<input type="text" v-model="formData.address" value="" placeholder="镇、街道、小区名、门牌号" />
					</view>
				</view>
			</view>
		</view>
		<view class="goods-contianer">
			<view class="goods-list" v-for="(item,index) in shoppingCard" :key="index" >
				<view v-if="item.name"  class="goods-item-shop" @click="go('./index?id='+item.id)">
					<i class="hd-icon">&#xe767;</i>
					<span>{{item.name}}</span>
					<i class="hd-icon">&#xe601;</i>
				</view>
				<view v-else  class="goods-item-shop" >
					<i class="hd-icon">&#xe767;</i>
					<span>暂无店铺名称</span>
					<i class="hd-icon">&#xe601;</i>
				</view>
				<view v-for="(goods, indexItem) in item.list" :key="indexItem">
					<view class="goods-item-top">
						<image  :src="goods.logo"  @click="go('/pages/goods/details?id='+goods.id)"/>
						<view class="goods-item">
							<h3>{{goods.title}}</h3>
							<div>
								<h4>{{goods.sku_name?'规格：'+goods.sku_name:''}}</h4>
							</div>
                            <view class="grace-space-between" style="margin-top:10rpx;">
                                <text  class="grace-shoppingcard-goods-price">￥{{goods.money}}</text>
                                <view class="grace-shoppingcard-goods-number">
                                	<view style="margin-right:20rpx;" class="numbutton" @tap="clearNum(goods,index,indexItem,item)">-</view>
                                	<view class="num">{{goods.buyNum}}</view>
                                	<view style="margin-left:20rpx;" class="numbutton" @tap="addNum(goods,index,indexItem,item)">+</view>
                                </view>
                            </view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="item-input">
			<label>留言</label>
			<view class="msg" >
				<input placeholder-style="color:#ccc" type="text" v-model="beizhu" placeholder="有什么想对商家说的可以写在这里哦~" />
			</view>
		</view>
		<view class="item-input">
			<label>快递运费</label>
			<p>{{addressPrice==0?'免运费':'10元'}}</p>
		</view>
		<view class="item-input">
			<label>店铺合计</label>
			<p>共{{cont}}件 <span>￥{{totalprice}}</span></p>
		</view>
		<order-bottom v-if="!graceAddressPickerShow" @shop="shopOrder" :price="totalprice"></order-bottom>
		<fab :topBtn="isTopBtn"></fab>
        <graceAddressPicker :show="graceAddressPickerShow" @confirm="pickerConfirm" @close="closePicker" cancelTColor="关闭"></graceAddressPicker>
	</view>
</template>

<script>
	import fab from '@/components/fab'
	import { orderCart,getExpress,batchSaveOrderCart } from '@/api/goods';
	import { userAddress } from '@/api/address';
	import { getAuth,getAuthData,loginAuth,setAuthFace,setAuth } from '@/api/user';
    import { cart_confirm } from '@/api/payment'
    import graceAddressPicker from '@/graceUI/components/graceAddressPicker.vue';
    var  graceChecker = require("@/graceUI/jsTools/graceChecker.js");
	import { saveUserAddress } from '@/api/address';
	export default{
		data(){
			return{
                graceAddressPickerShow : false,
				isTopBtn:false,
				shoppingCard:[],
				totalprice:'',
				dataInfo:{},
				addressData:'',
				addressId:'',
				cont:'',
				addressPrice:'',
				beizhu:'',
                province:'',
                city:'',
                qu:'',
                formData:{
                    name:'',
                    mobile:'',
                    area:'',
                    address:'',
                },
                goods_id:'',
                sku_data_id:'',
                num:''
                
			}
		},
		computed:{
		  userInfo(){
		      return getAuth();
		  }  
		},
		components:{
			fab,
            graceAddressPicker
		},
		onShow(){
            this.getData();
		},
		onLoad(e) {
		},
		onPageScroll(e){
			if(e.scrollTop>=400){
				this.isTopBtn=true
			}
			if(e.scrollTop<=100){
				this.isTopBtn=false
			}
		},
		methods:{
            openPicker() {
            	this.graceAddressPickerShow = true;
            },
            closePicker : function () {
            	this.graceAddressPickerShow = false;
            },
            pickerConfirm : function(e){
            	this.formData.area = e.names[0]+' '+e.names[1]+' '+e.names[2];
                this.province = e.names[0];
                this.city = e.names[1];
                this.qu = e.names[2];
            	this.closePicker();
            },
            getData(){
                let datas = JSON.parse(this.$Shop.getStorage('orderCar')).data;
                let goodsId=[],sku_data_id=[],num=[];
                datas.goodsList.forEach((item)=>{
                    item.list.forEach((item)=>{
                        goodsId.push(item.id)
                        sku_data_id.push(item.cartId)
                        num.push(item.buyNum)
                    })
                })
                this.goods_id =  goodsId.join(',');
                this.sku_data_id =  sku_data_id.join(',');
                this.num =  num.join(',');
                for(var key in datas){
                    if((typeof datas[key])=='object'){
                        this.shoppingCard=datas[key];
                    }else{
                        this.dataInfo[key]=datas[key]
                    }
                }
                this.totalprice = this.dataInfo.allGoodsMoney;
                if(this.totalprice<50){
                    this.addressPrice = 10;
                }else{
                     this.addressPrice = 0;
                }
                this.totalprice = this.dataInfo.allGoodsMoney+this.addressPrice;
                this.cont = this.dataInfo.allGoodsNum;
            },
			cartShopData(){
				if(this.$Shop.getStorage('shopCar')){ 
					let datas = JSON.parse(this.$Shop.getStorage('shopCar')).data;
					if(datas){
						let goodsId=[],sku_data_id=[],num=[];
						datas.goodsList.forEach((item)=>{
						    item.list.forEach((item)=>{
						        goodsId.push(item.id)
						        sku_data_id.push(item.cartId)
						        num.push(item.buyNum)
						    })
						})
						this.goods_id =  goodsId.join(',');
						this.sku_data_id =  sku_data_id.join(',');
						this.num =  num.join(',');
					}
				}
			},
            addNum(item, index, indexItem,goods) {
            	item.buyNum++
            	this.shoppingCard[index].list[indexItem].buyNum = item.buyNum;
                item.moneyAll =  item.buyNum*item.money
            	let data= {
					checked:true,
            		id:goods.id,
            		name:goods.name,
            		list:[item]
            	}
            	this.$Shop.setGoodsCart(data)
            	this.$Shop.setOrderCart(data)
            	this.getData();
            },
            clearNum(item, index, indexItem,goods) {
            	if (item.buyNum <= 1) {
            		return
            	}
            	item.buyNum--
            	this.shoppingCard[index].list[indexItem].buyNum = item.buyNum;
                item.moneyAll =  item.buyNum*item.money
                let data= {
					checked:true,
                	id:goods.id,
                	name:goods.name,
                	list:[item]
                }
				this.$Shop.setGoodsCart(data)
                this.$Shop.setOrderCart(data)
				this.getData();
            },
			setAddress(){
				uni.navigateTo({
					url:'/pages/personal/address'
				})
			},
			go(url){
				uni.navigateTo({
					url
				})
			},
			shopOrder(){
                var rule = [
                	{ name: "name", checkType: "string", checkRule: "1,10", errorMsg: "收货人姓名应为1-20个字符" },
                	{ name: "mobile", checkType: "phoneno", checkRule: "", errorMsg: "请正确填写手机号" },
                	{ name: "area", checkType: "string", checkRule: "1,100", errorMsg: "请选择所在地区" },
                	{ name: "address", checkType: "string", checkRule: "1,100", errorMsg: "请正确填写详细地址" }
                ];
                var formData = this.formData;
                var checkRes = graceChecker.check(formData, rule);
                if(checkRes){
                    formData.province= this.province;
                    formData.city = this.city;
                    formData.qu =this.qu;
                    formData.beizhu = this.beizhu;
                    loginAuth(formData.mobile).then((res)=>{
                        uni.showToast({
							title:res.data.msg,
							icon:'none'
						})
						if(res.data.status==1){
							//注册新用户，记录token
							setAuth(res.data.datas.session_id,res.data.datas.username)
							setAuthFace(res.data.datas.face)
							//设置收货地址
							saveUserAddress({
								province:formData.province,
								city:formData.city,
								qu:formData.qu,
								username:formData.mobile,
								mobile:formData.mobile,
								name:formData.name,
								area:formData.area,
								address:formData.address
							}).then((resAddress)=>{
								if(resAddress.data.status==1){  //地址添加成功
									userAddress(formData.mobile).then((resDress)=>{ //获取地址列表
										if(resDress.data.status==1){
                                            this.addressData = resDress.data.datas[0]
                                            this.addressId =  resDress.data.datas[0].id;
                                        }        
                                        batchSaveOrderCart({ //添加至购物车
                                            username:formData.mobile,
                                            goods_id:this.goods_id,
                                            sku_data_id:this.sku_data_id?this.sku_data_id:0,
                                            num:this.num
                                        }).then((resGoods)=>{
                                            uni.showToast({
                                            	title:resGoods.data.msg,
                                            	icon:'none'
                                            })
                                            if(resGoods.data.status==1){
                                                orderCart({  //获取购物车
                                                	'username': formData.mobile
                                                }).then((resCarts) => {
                                                	let shoppingCard = [];
                                                	let datas = resCarts.data.datas;
                                                    let goods_id = [];
                                                	for (var key in datas) {
                                                		if ((typeof datas[key]) == 'object') {
                                                			shoppingCard = datas[key];
                                                		} 
                                                	}
                                                	for (var i = 0; i < shoppingCard.length; i++) {
                                                		for (var ii = 0; ii < shoppingCard[i].list.length; ii++) {
                                                			goods_id.push(shoppingCard[i].list[ii].cartId)
                                                		}
                                                	}
                                                    let text;
                                                    // #ifdef MP-WEIXIN
                                                        text='wxapp'
                                                    // #endif
                                                    
                                                    // #ifdef MP-BAIDU
                                                        text='bdapp'
                                                    // #endif
													
                                                    // #ifdef APP-PLUS
                                                        text='app'
                                                    // #endif
                                                    cart_confirm(formData.mobile,goods_id.join(','),this.addressId,formData.beizhu,text).then((resCart)=>{
														if(resCart.data.status==1){
															this.cartShopData();
															if(this.goods_id){
																batchSaveOrderCart({ //添加至购物车
																    username:formData.mobile,
																    goods_id:this.goods_id,
																    sku_data_id:this.sku_data_id,
																    num:this.num
																}).then((resOrderGoods)=>{
																})
															}
															uni.reLaunch({
															    url: './payment?orderId='+resCart.data.datas.orderId
															});
                                                    	}
                                                    })
                                                })
                                                
                                            }
                                        })
									})
								}
							})
						}
						
						
                    })
                }else{
                    uni.showToast({ title: graceChecker.error, icon: "none" });
                }
				/* if(this.addressData.id==''){
					uni.showToast({
					    title: '请选择地址！',
					});
					return
				}
				cart_confirm(this.userInfo.username,this.ids,this.addressData.id,this.beizhu).then((res)=>{
					if(res.data.status==1){
						uni.redirectTo({
						    url: './payment?orderId='+res.data.datas.orderId
						});
					}
				}) */
			}
		}
	}
</script>

<style lang="scss">
    .grace-shoppingcard-goods-price {
    	color: #ed1475;
    	font-size: 32rpx;
    	display: flex;
    	flex-wrap: nowrap;
    	justify-content: space-between;
    }
    
    .grace-shoppingcard-goods-number {
    	padding: 2px 0;
    	display: flex;
    	justify-content: flex-start;
    	align-items: center;
    
    	.numbutton {
    		font-size: 40rpx;
    	}
    
    	.num {
    		padding: 10rpx 20rpx;
    		background: #f1f2f3;
    
    	}
    }
	.addressPush-list{
		background: #fff;
		padding:20rpx;
		.h3{
			width:140rpx;
			font-size:24rpx;
			color:#333;
		}
		.li{
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom:20rpx;
			.address-input{
				input{
					margin-bottom:20rpx;
					&:nth-last-of-type(1){
						margin-bottom: 0;
					}
				}
			}
			.div{
				width:540rpx;
				input{
					padding:10rpx 20rpx;
					border:1px solid #eee;
					font-size:24rpx;
				}
			}
		}
	}
	.address-list{
		li{
			margin:30rpx 0;
			padding:30rpx 0;
			.item-address{
				display: flex;
				justify-content: space-between;
				align-items: center;
				&>.hd-icon{
					margin-right:20rpx;
					color:#666;
					font-size:28rpx;
				}
			}
			background: url() no-repeat;
			background-size:100% 100%;
			.address-list-left{
				margin-left:20rpx;
				width:680;
				.address-list-left-top{
					display: flex;
					justify-content: flex-start;
					align-items: center;
					margin-bottom:20rpx;
					h3{
						color:#343434;
						font-size:28rpx;
						margin-right:10rpx;
						span{
							color:#f37ca3;
							font-size:36rpx;
							margin-right:4rpx;
						}
					}
				}
				.address-list-left-bottom{
					color:#777;
					font-size:28rpx;
				}
			}
		}
	}
	.add{
		li{
			display: flex;
			justify-content: space-between;
			align-items: center;
			&>.hd-icon{
				margin-right:20rpx;
				color:#666;
				font-size:28rpx;
			}
		}
		.address-list-left-top{
			margin-left:20rpx;
			h3{
				color:#343434;
				font-size:28rpx;
				margin-right:10rpx;
				span{
					color:#f37ca3;
					font-size:36rpx;
					margin-right:4rpx;
				}
			}
		}
	}
	.goods-contianer{
		margin-top:30rpx;
		background: #fff;
		.goods-list{
			border-bottom: 1rpx solid #eee;
			.goods-item-shop{
				width:710rpx;
				margin:0 auto;
				border-bottom: 1rpx solid #eee;
				display: flex;
				justify-content: flex-start;
				padding:20rpx 0;
				align-items: center;
				i{
					margin-right:8rpx;
				}
			}
			.goods-item-top{
				width:710rpx;
				margin:0 auto;
				display: flex;
				justify-content: space-between;
				padding:20rpx 0;
				image{
					width:140rpx;
					height:140rpx;
				}
				.goods-item{
					width:550rpx;
					h3{
						color:#333;
						display: -webkit-box;
						text-overflow: ellipsis;
						overflow: hidden;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						font-size:28rpx;
					}
					div{
						margin-top:10rpx;
						display: flex;
						justify-content: space-between;
						h4{
							font-size:28rpx;
							color:#ababab;
						}
						h5{
							color:#9E9E9E;
							font-size:24rpx;
							span{
								color:#E91E63;
								margin-left:14rpx;
								font-weight: bold;
							}
						}
					}
				}
			}
		}
	}
	.item-input{
		display: flex;
		justify-content:space-between;
		background: #fff;
		border-bottom:1px solid #eee;
		padding:30rpx 0;
		&:nth-last-of-type(1){
			margin-bottom:40rpx;
		}
		label{
			margin-left:20rpx;
			color:#333;
			font-size:28rpx;
		}
		.msg{
			display: block;
			width:600rpx;
		}
		input{
			margin-right:20rpx;
			color:#333;
			font-size:28rpx;
		}
		p{
			margin-right:20rpx;
			color:#999;
			font-size:28rpx;
			span{
				color:#fd8197;
				margin-left:10rpx;
				font-weight: bold;
			}
		}
	}
</style>
